package xyz.bali16.module.activeuser.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gitee.starblues.bootstrap.annotation.AutowiredType;
import com.gitee.starblues.spring.MainApplicationContext;
import com.gitee.starblues.spring.SpringBeanFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import xyz.bali16.application.core.enums.ApiEnum;
import xyz.bali16.application.core.model.Result;
import xyz.bali16.application.core.model.UserVo;
import xyz.bali16.application.entity.User;
import xyz.bali16.application.service.UserService;
import xyz.bali16.module.activeuser.entity.ActiveUser;
import xyz.bali16.module.activeuser.model.ActiveUserAddParam;
import xyz.bali16.module.activeuser.model.ActiveUserPageParam;
import xyz.bali16.module.activeuser.model.ActiveUserUpdateParam;
import xyz.bali16.module.activeuser.service.ActiveUserService;

import javax.validation.Valid;

import java.util.List;

import static xyz.bali16.application.core.model.Result.*;
import static xyz.bali16.application.core.utils.ResultUtils.errorLog;

/**
 * @author bali2 on 9/3/2023.
 * @version 1.0
 */
@RestController
@RequestMapping(BaseController.API + "active/user")
@Api(tags = "活跃用户信息接口")
@AllArgsConstructor

public class ActiveUserController extends BaseController {
    public static final Logger logger = LoggerFactory.getLogger(ActiveUserController.class);
    @Autowired
    ActiveUserService activeUserService;

    @Autowired
    private MainApplicationContext context;

    @GetMapping
    @ApiOperation("分页条件查询活跃用户信息")
    //@PreAuthorize("@auth.permission('plugin:activeUser:query')")
    public Result<IPage<ActiveUser>> pageQuery(@Valid ActiveUserPageParam param) {
        IPage<ActiveUser> activeUserIPage = activeUserService.getPage(param);
        List<ActiveUser> activeUserList = activeUserIPage.getRecords();
        SpringBeanFactory factory = context.getSpringBeanFactory();
        UserService userService = factory.getBean(UserService.class);
        for (ActiveUser activeUser : activeUserList) {
            String userId = activeUser.getUserId();
            User user = userService.getById(userId);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            activeUser.setUserVo(userVo);
        }
        activeUserIPage.setRecords(activeUserList);
        return success(ApiEnum.GET_SUCCESS, activeUserIPage);
    }

    @PostMapping
    //@PreAuthorize("@auth.permission('plugin:activeUser:add')")
    @ApiOperation("添加活跃用户信息")
    public Result<String> add(@RequestBody @Valid ActiveUserAddParam param) {
        try {
            activeUserService.addActiveUser(param);
            return response(ApiEnum.ADD_SUCCESS);
        } catch (Exception e) {
            errorLog(logger, e, "新增活跃用户信息，信息失败 {}", e.getMessage());
            return failure(ApiEnum.ADD_ERROR, "新增活跃用户信息失败", e);
        }
    }

    @PutMapping
    //@PreAuthorize("@auth.permission('plugin:activeUser:update')")
    @ApiOperation("修改活跃用户信息")
    public Result<String> update(@RequestBody @Valid ActiveUserUpdateParam param) {
        try {
            activeUserService.updateActiveUser(param);
            return response(ApiEnum.UPDATE_SUCCESS);
        } catch (Exception e) {
            errorLog(logger, e, "更新活跃用户信息 '{}' 信息失败 {}", param.getUserId(), e.getMessage());
            return failure(ApiEnum.UPDATE_ERROR, "更新活跃用户信息失败", e);
        }
    }

    @DeleteMapping("/{activeUserId}")
    //@PreAuthorize("@auth.permission('plugin:activeUser:delete')")
    @ApiOperation("删除活跃用户信息")
    @ApiImplicitParam(name = "activeUserId", value = "活跃用户信息id", paramType = "path", required = true)
    public Result<String> deleteActiveUser(@PathVariable("activeUserId") String activeUserId) {
        try {
            activeUserService.delete(activeUserId);
            return response(ApiEnum.DELETE_SUCCESS);
        } catch (Exception e) {
            errorLog(logger, e, "删除活跃用户信息 '{}' 失败. {}", activeUserId, e.getMessage());
            return failure(ApiEnum.DELETE_ERROR, e);
        }
    }

}
